package com.ls.blog.service;

import com.baomidou.mybatisplus.core.conditions.Wrapper;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.ls.blog.api.ArticleService;
import com.ls.blog.api.CommentsService;
import com.ls.blog.api.SysUserService;
import com.ls.blog.entity.Comment;
import com.ls.blog.mapper.CommentsMapper;
import com.ls.blog.result.ResultCode;
import com.ls.blog.utils.UserThreadLocal;
import com.ls.blog.vo.Author;
import com.ls.blog.vo.CommentsVo;
import com.ls.blog.vo.UserInfo;
import com.ls.blog.vo.params.CommentParam;
import com.ls.blog.vo.params.CommentsParam;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.text.SimpleDateFormat;
import java.util.*;

/**
 * @program: myblog
 * @author: lishun
 * @create: 2021-07-10 17:34
 **/
@Service
public class CommentsServiceImpl implements CommentsService {

    @Autowired
    private CommentsMapper commentsMapper;

    @Autowired
    private SysUserService sysUserService;

    @Autowired
    private ArticleService articleService;



    @Override
    public Map<String,Object> showComments(CommentsParam param) throws Exception {
        Page<Comment> page = new Page();
        page.setCurrent(param.getCurrent());
        page.setSize(5);
        QueryWrapper<Comment> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("article_id",param.getArticleId());
        queryWrapper.eq("level",1);
        /**
         * 1.首先根据文章id得到对应的评论信息
         */
        Page<Comment> commentPage = commentsMapper.selectPage(page, queryWrapper);

        /**
         * 2.将评论信息加工成vo对象
         */
        List<CommentsVo> commentsVos = copyCommentsList(commentPage.getRecords());
        Map<String,Object> map = new HashMap<>();
        map.put("commentList",commentsVos);
        map.put("count",page.getTotal());
        return map;
    }

    /**
     * 将根据commentsList组装新的commentsVoList
     * @param comments
     * @return
     */
    public  List<CommentsVo> copyCommentsList(List<Comment> comments) throws Exception {
        List<CommentsVo> commentsVos = new ArrayList<>();
        for (Comment comment:comments){
            CommentsVo commentsVo = copy(comment);
            commentsVos.add(commentsVo);
        }
        return commentsVos;
    }

    /**
     * 分页二级评论
     */
    @Override
    public List<CommentsVo> secondComments(Long current,Long id) throws Exception {
        QueryWrapper<Comment> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("parent_id",id);
        if (current==null){
            queryWrapper.last("limit 3");
            return copyCommentsList(commentsMapper.selectList(queryWrapper));
        }
        Page<Comment> page = new Page<>();
        page.setSize(5)
                .setCurrent(current);
        return copyCommentsList(commentsMapper.selectPage(page,queryWrapper).getRecords());
    }

    /**
     * 将comment转化为commentVo对象
     * @param comment
     * @return
     */
    public CommentsVo copy(Comment comment) throws Exception {
       CommentsVo commentsVo = new CommentsVo();
       BeanUtils.copyProperties(comment,commentsVo);
       if (commentsVo==null){
           throw new Exception("评论加载失败");
       }
        Author author =  sysUserService.getAuthorById(comment.getAuthorId());
        commentsVo.setAuthor(author);

        /**
         * 判断是否是一级评论
         */
        if (comment.getLevel()==1){
            List<CommentsVo> commentsVos = secondComments(null, comment.getId());
            commentsVo.setChildrens(commentsVos);
            QueryWrapper<Comment> queryWrapper = new QueryWrapper<>();
            queryWrapper.eq("parent_id",comment.getId());
            queryWrapper.eq("level",2);
            Integer integer = commentsMapper.selectCount(queryWrapper);
            commentsVo.setReplyCount(integer);
        }
        /**
         * 判断是否是二级评论
         */
        if (comment.getLevel() == 2) {
            Long toUid = comment.getToUid();
            Author author1 =  sysUserService.getAuthorById(toUid);
            commentsVo.setToUser(author1);
        }
        return commentsVo;
    }



//    @Override
//    @Transactional
//    public void comment(CommentParam commentParam) {
//
//        /**
//         * 1、从拦截器中获得用户信息
//         * 2、封装成一个comment插入到comment表中
//         * 3、判断是否是子评论
//         * 3、对应的文章表中的评论数量也应该加一，添加上事务支持
//         */
//        UserInfo userInfo = UserThreadLocal.get();
//        Comment comment = new Comment();
//        BeanUtils.copyProperties(commentParam,comment);
//        comment.setCreateDate(System.currentTimeMillis());
//        comment.setAuthorId(userInfo.getId());
//        Long parent = commentParam.getParent();
//        if (parent == null || parent==0){
//            comment.setLevel(1);
//        }else {
//            comment.setLevel(2);
//        }
//        comment.setParentId(parent==null?0:parent);
//        Long toUserId = commentParam.getToUserId();
//        comment.setToUid(toUserId==null ? 0:toUserId);
//        commentsMapper.insert(comment);
//        articleService.addCommentCountsByArticleId(commentParam.getArticleId());
//    }


    @Override
    public void comment(CommentParam commentParam) {
        if (commentParam==null && commentParam.getArticleId()==null){
            throw new RuntimeException(ResultCode.COMMENT_FAIL.getMessage());
        }
        Comment comment = new Comment();
        comment.setArticleId(commentParam.getArticleId());
        comment.setContent(commentParam.getContent());
        if (commentParam.getParentId()!=null){
            comment.setLevel(2);
            comment.setParentId(commentParam.getParentId());
            comment.setToUid(commentParam.getToUid());
        }else {
            comment.setLevel(1);
            comment.setParentId(0L);
            comment.setToUid(0L);
        }
        comment.setCreateDate(new Date().getTime());
        comment.setAuthorId(commentParam.getAuthorId());
        commentsMapper.insert(comment);
    }
}
